package com.cloudkinto.service.consumer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cloudkinto.common.RabbitQueueConstant;
import com.cloudkinto.dao.AsyncJobDao;
import com.cloudkinto.entity.AsyncJobDo;
import com.cloudkinto.service.job.AsyncJobService;
import com.cloudkinto.service.platform.PlatformOrderExportService;
import com.cloudkinto.service.platform.vo.AsyncFinishConsumerReq;
import com.cloudkinto.service.platform.vo.AsyncUpdateConsumerReq;
import com.cloudkinto.service.platform.vo.PlatOrderExportConsumerReq;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class PlatformOrderExportConsumer {
    private final PlatformOrderExportService platformOrderExportService;
    private final AsyncJobDao asyncJobDao;
    private final AsyncJobService asyncJobService;

    @RabbitListener(queuesToDeclare = @Queue(RabbitQueueConstant.Export_PlatformOrder))
    public void platformOrderExport(String msg) {
        PlatOrderExportConsumerReq req = JSONObject.parseObject(msg, PlatOrderExportConsumerReq.class);
        try {
            platformOrderExportService.exportAsync(req.getMap(), req.getTaskId());
        } catch (Exception e) {
            e.printStackTrace();
            LambdaUpdateWrapper<AsyncJobDo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(AsyncJobDo::getId, req.getTaskId()).set(AsyncJobDo::getStatus, 4).set(AsyncJobDo::getErrorMsg, e.getMessage());
            asyncJobDao.update(null, wrapper);
        }
    }


    @RabbitListener(queuesToDeclare = @Queue(RabbitQueueConstant.Export_AsyncDo_Update))
    public void asyncJobUpdate(String msg) {
        AsyncUpdateConsumerReq req = JSONObject.parseObject(msg, AsyncUpdateConsumerReq.class);
        try {
            asyncJobService.updateRows(req.getId(), req.getStatus(), req.getRows(), req.getErrorMsg());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queuesToDeclare = @Queue(RabbitQueueConstant.Export_AsyncDo_Finish))
    public void asyncJobFinish(String msg) {
        AsyncFinishConsumerReq req = JSONObject.parseObject(msg, AsyncFinishConsumerReq.class);
        try {
            asyncJobService.updateFinish(req.getId(), req.getResultUrl());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
